package cn.xuqiudong.backend.config.mybatis;

import cn.xuqiudong.backend.base.helper.SaSessionHelper;
import cn.xuqiudong.backend.base.helper.SessionUserInfo;
import cn.xuqiudong.common.base.model.BaseEntity;
import cn.xuqiudong.common.base.mybatis.CommonFieldInterceptor;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 描述:
 * mybatis配置
 *
 * @author Vic.xu
 * @since 2025-03-20 14:58
 */
@Configuration
public class MybatisConfig {

    /**
     * mybatis 通用字段拦截器
     */
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return configuration -> {
            configuration.addInterceptor(new CommonFieldInterceptor(
                    (o) -> {
                        // 插入时填充字段
                        if (o instanceof BaseEntity) {
                            SessionUserInfo user = SaSessionHelper.getUser();
                            if (user == null) {
                                return;
                            }
                            BaseEntity baseEntity = (BaseEntity) o;
                            if (baseEntity.getCreateId() == null) {
                                baseEntity.setCreateId(user.getUserId());
                            }
                            if (baseEntity.getUpdateId() == null) {
                                baseEntity.setUpdateId(user.getUserId());
                            }
                            if (baseEntity.getVersion() == null) {
                                baseEntity.setVersion(1);
                            }
                        }
                    },
                    (o) -> {
                        //更新时填充字段
                        if (o instanceof BaseEntity) {
                            SessionUserInfo user = SaSessionHelper.getUser();
                            if (user == null) {
                                return;
                            }
                            BaseEntity baseEntity = (BaseEntity) o;
                            if (baseEntity.getUpdateId() == null) {
                                baseEntity.setUpdateId(user.getUserId());
                            }
                            if (baseEntity.getVersion() != null) {
                                baseEntity.setVersion(baseEntity.getVersion().intValue() + 1);
                            }
                        }
                    }
            ));
        };
    }
}
